package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicCustomer;
import com.bzkj.basicinfo.domain.ncc.dto.NccBasicCustomerDto;
import com.bzkj.basicinfo.domain.ncc.erp.CustomerBean;
import com.bzkj.basicinfo.mapper.NccBasicCustomerMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicCustomerService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 客户信息：6
 */
@Service("nccJobCustomerService")
@Slf4j
public class NccBasicCustomerServiceImpl implements NccBasicCustomerService {
    @Autowired
    private NccBasicCustomerMapper nccBasicCustomerMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private String url;

    @Value("${ncc.basicInfoUrl}")
    private String basicInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Override
    public void updateNccBasicCustomerJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(6, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(6);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicCustomer> basicCustomers = dataArray.toList(NccBasicCustomer.class);
                for (NccBasicCustomer basicCustomer : basicCustomers) {
                    NccBasicCustomer basicCustomer1 = nccBasicCustomerMapper.queryNccBasicCustomer(basicCustomer.getCode());
                    if (basicCustomer1 != null) {
                        nccBasicCustomerMapper.updateNccBasicCustomer(basicCustomer);
                    } else {
                        nccBasicCustomerMapper.insertNccBasicCustomer(basicCustomer);
                    }
                }
            }
        }
    }

    /**
     * ncc客户基础信息新增
     *
     * @param entity
     * @Author wangzhichao
     * @Date 2024/12/05 08:35:01
     */
    @Override
    public AjaxResult nccBasicCustomerSave(NccBasicCustomer entity) {
        NccBasicCustomer customer = nccBasicCustomerMapper.queryNccBasicCustomer(entity.getCode());
        if (Objects.isNull(customer)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            try {
                entity.setCuststate(String.valueOf(1));
                entity.setMnecode(getCapitalInitials(entity.getName()));
                entity.setpK_ORG("0001A1100000000021CH");
                entity.setpK_GROUP("0001A1100000000021CH");
                entity.setModifier(user.getUserName());
                entity.setModifiedtime(new Date());
                entity.setCreator(user.getUserName());
                entity.setCreationtime(new Date());
                entity.setTs(new Date());
                synchronized (this) {
                    String pkCustomer = "WMS" + uniq.generateUniqueIdentifier();
                    entity.setpK_CUSTOMER(pkCustomer);
                }
                nccBasicCustomerMapper.insertNccBasicCustomer(entity);
                return AjaxResult.success("新增成功");
            } catch (Exception e) {
                log.error("用户基础信息新增失败:", e);
                return AjaxResult.error("新增失败");
            }
        } else {
            return AjaxResult.error("客户代码重复");
        }
    }

    public String getCapitalInitials(String chinese) {
        StringBuilder initials = new StringBuilder();
        char[] chars = chinese.toCharArray();
        for (char ch : chars) {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]")) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    initials.append(pinyinArray[0].substring(0, 1).toUpperCase());
                }
            } else {
                initials.append(ch);
            }
        }
        return initials.toString();
    }

    /**
     * ncc客户基础信息状态修改
     *
     * @param status
     * @param pkCustomer
     * @Author wangzhichao
     * @Date 2024/12/05 09:53:32
     */
    @Override
    public AjaxResult nccBasicCustomerEnableStatusUpdate(String status, String pkCustomer) {
        try {
            String userName = SecurityUtils.getLoginUser().getUser().getUserName();
            int i = nccBasicCustomerMapper.nccBasicCustomerEnableStatusUpdate(status, pkCustomer, userName);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定客户信息");
        } catch (Exception e) {
            log.error("状态修改失败:", e);
            return AjaxResult.error("状态修改失败");
        }
    }

    /**
     * 根据pK_CUSTOMER修改客户信息
     *
     * @param entity
     * @Author wangzhichao
     * @Date 2024/12/05 14:22:44
     */
    @Override
    public AjaxResult nccBasicCustomerUpdate(NccBasicCustomer entity) {
        NccBasicCustomer customer = nccBasicCustomerMapper.queryNccBasicCustomer(entity.getCode());
        try {
            if (Objects.isNull(customer)) {
                int i = nccBasicCustomerMapper.nccBasicCustomerUpdate(entity);
                return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
            } else {
                if (customer.getpK_CUSTOMER().equals(entity.getpK_CUSTOMER())) {
                    nccBasicCustomerMapper.nccBasicCustomerUpdate(entity);
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("客户代码重复使用");
                }
            }
        } catch (Exception e) {
            log.error("修改失败:" + e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据条件分页查询数据
     *
     * @Author wangzhichao
     * @Date 2024/12/05 15:27:03
     * @Param dto 条件
     * @Param page 分页条件
     */
    @Override
    public List<NccBasicCustomer> findNccBasicCustomerDataPage(NccBasicCustomerDto dto) {
        // 获取分页数据
        return nccBasicCustomerMapper.findNccBasicCustomerDataPage(dto);
    }

    @Override
    public List<String> findNccBasicCustomerName(String name) {
        return nccBasicCustomerMapper.findNccBasicCustomerName(name);
    }


    @Autowired
    private HttpClientUtils hcu;

    /**
     * 定时同步当前客户信息
     *
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 6, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<CustomerBean> list = jsonNode.getJSONArray("data").toJavaList(CustomerBean.class);
        if (!list.isEmpty())
            extracted(list);

        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<CustomerBean> list) {
        for (CustomerBean customerBean : list) {
            nccBasicCustomerMapper.insertOrUpdate(customerBean);
        }
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i) {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }
}
